package com.itheima.service.imlp;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Mapper.OrdersMapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.*;
import com.itheima.exection.DeleteByIdDishCustomExection;
import com.itheima.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl
        extends ServiceImpl<OrdersMapper, Orders>
        implements IOrdersService {

//    注入用户的业务层
    @Autowired
    private IUserService userService;
//    注入购物车的业务层
    @Autowired
    private IShoppingCartService shoppingCartService;
//    注入地址业务层
    @Autowired
    private IAddressBookService addressBookService;
//    注入订单明细表
    @Autowired
    private IOrderDetailService orderDetailService;


//    Orders
//    (id=null, number=null, status=null,
//    userId=null, addressBookId=1604787620990058498,
//    orderTime=null, checkoutTime=null, payMethod=1,
//    amount=null, remark=, userName=null, phone=null,
//    address=null, consignee=null)
    @Override
    public void submit(Orders orders) {
//        订单表需要补全的内容


//        从域中获得用户ID
        Long uesrId = BaseContext.getCurrentId();
        if (uesrId==null){
            throw new DeleteByIdDishCustomExection("请先登录。");
        }


//        A. 获得当前用户id, 查询当前用户的购物车数据

//        获取用户购物车中的数据
        LambdaQueryWrapper<ShoppingCart> shoppingWrapper = new LambdaQueryWrapper<>();
//        根据用户ID查询
        shoppingWrapper.eq(ShoppingCart::getUserId,uesrId);
        List<ShoppingCart> shoppingList = shoppingCartService.list(shoppingWrapper);
//        判断用户的购物车是不是null
        if (shoppingList==null){
            throw new DeleteByIdDishCustomExection("当前购物车没有商品，请重新尝试。");
        }


//        B. 根据当前登录用户id, 查询用户数据
        User user = userService.getById(uesrId);


//        C. 根据地址ID, 查询地址数据
//        从封装类中获取地址ID
        Long addressBookId = orders.getAddressBookId();
        AddressBook address = addressBookService.getById(addressBookId);
        if (address==null){
            throw new DeleteByIdDishCustomExection("当前地址为空，请添加后，再尝试");
        }


//        D. 组装订单明细数据, 批量保存订单明细
        //     订单明细表需要补全的内容
        //    名称： name;
        //    订单id： orderId; //手动赋值
        //    菜品id： dishId;
        //    套餐id：setmealId;
        //    口味：dishFlavor;
        //    数量： number;
        //    金额：amount;
        //    图片：image;

//        此处使用MybatisPlus提供的功能
        long orderId = IdWorker.getId();//获取订单号
        AtomicInteger amount = new AtomicInteger(0);


//        组装订单明细数据，当前订单明细数据与购物车表差不多，可以用购物车表进行赋值（多表）
        List<OrderDetail> orderDetailList = shoppingList.stream().map(shoppingCart -> {
//            创建订单明细对象
            OrderDetail od = new OrderDetail();
            od.setName(shoppingCart.getName());
            od.setOrderId(orderId);
            od.setDishId(shoppingCart.getDishId());
            od.setSetmealId(shoppingCart.getSetmealId());
            od.setDishFlavor(shoppingCart.getDishFlavor());
            od.setNumber(shoppingCart.getNumber());
            od.setAmount(shoppingCart.getAmount());
            od.setImage(shoppingCart.getImage());
//            累计计算金额
//            addAndGet先增加再返回方法
//            调用原始数据
//            multiply()乘
//            数量
            amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return od;
        }).collect(Collectors.toList());


//        E. 组装订单数据, 批量保存订单数据（单表）
        //    订单号：number=null,                              //long orderId = IdWorker.getId()
        //    用户ID：userId=null,                             //通过域中的数据获得uesrId
        //    地址ID：addressBookId=1604787620990058498,       //封装类中有
        //    下单时间：orderTime=null,                         //当前时间
        //    支付时间：checkoutTime=null，                     //当前时间
        //    实收金额： amount=null
        //    用户名：userName=null,                            //User user = userService.getById(uesrId);
        //    手机号：phone=null,                               //address获取
        //    地址：address=null,                              //address获取
        //    收货人：consignee=null                           //address获取


        orders.setAmount(new BigDecimal(amount.get()));
        orders.setNumber(String.valueOf(orderId));
        orders.setUserId(uesrId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setUserName(user.getName());
        orders.setPhone(address.getPhone());
        orders.setConsignee(address.getConsignee());
        orders.setStatus(2);
        orders.setAddress(
                (address.getProvinceName()==null?"":address.getProvinceName())+
                (address.getCityName()==null?"":address.getCityName())+
                (address.getDistrictName()==null?"":address.getDistrictName())+
                (address.getDetail()==null?"":(address.getDetail())));

//        向订单表中存储数据
        this.save(orders);
//        向订单明细表中存储数据
        orderDetailService.saveBatch(orderDetailList);


//        F. 删除当前用户的购物车列表数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,uesrId);
        shoppingCartService.remove(wrapper);

    }



}
